#!/usr/bin/env python2
# coding=utf-8

import sys
import os
import time

"""
old heads
# VSCode
#
# 标签（空格分隔）： VSCode IDE
#
# ---

==>

new heads
---
title: 'VSCode'
tags: [VSCode, IDE]
categories: 通用
date: 2019-11-08 10:27:12
---
"""


def read_lines(fp):
    """读全部文件，需要自己strip()
    """
    with open(fp, "r") as f:
        lines = f.readlines()
        return lines


def write_lines(fp, lines):
    """写全部内容，需要自己加上\n
    """
    with open(fp, "w+") as f:
        f.writelines(lines)


def main():
    lines = read_lines(fp)
    heads = []
    for line in lines:
        heads.append(line)
        if line.startswith('---'):
            break
    tails = lines[len(heads):]
    title = heads[0].strip().split('#')[-1].strip()
    tags = []
    for line in heads:
        line = line.strip()
        if line.startswith('标签'):
            tags = line.split('：')[-1].strip().split(' ')
            break
    heads_new = []
    heads_new.append("---")
    heads_new.append('title: %s' % title)
    heads_new.append('tags: %s' % tags)
    heads_new.append('categories: 通用')
    heads_new.append('date: %s' % time.strftime('%Y-%m-%d %H:%M:%S'))
    heads_new.append("---")

    # for line in heads_new:
    #     print line
    # print tails[0]
    # print tails[1]
    # print tails[2]
    # print tails[3]

    lines = [line + '\n' for line in heads_new]
    lines.extend(tails)

    write_lines(fp, lines)


if __name__ == "__main__":
    fp = sys.argv[1]
    if not os.path.exists(fp):
        print "file not exists"
        sys.exit()
    main()
